package com.vq3.digitalizationsoftwareintegrates.Servlet.User;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vq3.digitalizationsoftwareintegrates.Entity.Enum.Group_Type;
import com.vq3.digitalizationsoftwareintegrates.Entity.Info.ResultInfo;
import com.vq3.digitalizationsoftwareintegrates.Entity.User.*;
import com.vq3.digitalizationsoftwareintegrates.Entity.UserManageCenter.UserManageCenterEntity;
import com.vq3.digitalizationsoftwareintegrates.Entity.UserManageCenter.UserManageCenterEntity_perEntity;
import com.vq3.digitalizationsoftwareintegrates.Service.Index.IndexSoftwareService;
import com.vq3.digitalizationsoftwareintegrates.Service.User.UserFusionService;
import com.vq3.digitalizationsoftwareintegrates.Service.User.UserLoginService;
import com.vq3.digitalizationsoftwareintegrates.Utils.ImageUtil.CalculationIsType;
import com.vq3.digitalizationsoftwareintegrates.Utils.PackagedDataUtil.Impl.PackagedDataImpl;
import com.vq3.digitalizationsoftwareintegrates.Utils.PackagedDataUtil.PackagedData;
import com.vq3.digitalizationsoftwareintegrates.Utils.PermissionControl.GetUserPermission;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("userFusion")
public class UserFusionServlet {
    @Resource
    UserFusionService userFusionService;
    @Resource
    UserLoginService userLoginService;
    @Resource
    IndexSoftwareService indexSoftwareService;
    @Resource
    GetUserPermission getUserPermission;

    @RequestMapping("getUserManageCenterSideBar")
    public void getUserManageCenterSideBar(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        ResultInfo resultInfo = new ResultInfo();
        PackagedData packagedData = new PackagedDataImpl();

        UserEntity userEntity = (UserEntity)httpServletRequest.getSession().getAttribute("USER");
        List<Permission_TBEntity> permission_tbEntities = getUserPermission.GetPermission(userEntity.getUname());
        Set<Integer> um_idS = new HashSet<>();
        resultInfo.setFlag(false);
        if (!permission_tbEntities.isEmpty()){
            for (Permission_TBEntity permission_tbEntity : permission_tbEntities){
                List<UserManageCenterEntity_perEntity> userManageCenterEntity_perEntities = userFusionService.perFindUMId(permission_tbEntity);
                if (!userManageCenterEntity_perEntities.isEmpty()) {
                    for (UserManageCenterEntity_perEntity userManageCenterEntity_perEntity : userManageCenterEntity_perEntities) {
                        um_idS.add(userManageCenterEntity_perEntity.getUmid());
                    }
                }
            }

        }
        List<UserManageCenterEntity> userManageCenterEntities = userFusionService.umidFindUMSideBar(um_idS);
        if (!userManageCenterEntities.isEmpty()) {
            resultInfo.setFlag(true);
            resultInfo.setData(userManageCenterEntities);
        }
        packagedData.writeValue(resultInfo,httpServletResponse);


    }

    @RequestMapping("CalculationGroupType")
    public void calculationGroupType(@RequestParam String groupID, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        Group_TBEntity group_tbEntity = userFusionService.calculationGroupType(Integer.parseInt(String.valueOf(groupID)));
        ResultInfo resultInfo = new ResultInfo();
        PackagedData packagedData = new PackagedDataImpl();
        resultInfo.setFlag(group_tbEntity != null);
        resultInfo.setData(group_tbEntity);
        packagedData.writeValue(resultInfo,httpServletResponse);
    }
    @RequestMapping("findAllGroupType")
    public void findAllGroupType( HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {

        ResultInfo resultInfo = new ResultInfo();
        PackagedData packagedData = new PackagedDataImpl();
        resultInfo.setData(userFusionService.findAllGroupType());
        packagedData.writeValue(resultInfo,httpServletResponse);
    }

    @RequestMapping("getAllUserData")
    public void getAllUserData(@RequestParam int page ,HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException, ServletException {
        ResultInfo resultInfo = new ResultInfo();
        PackagedData packagedData = new PackagedDataImpl();
        UserEntity userEntity = (UserEntity)httpServletRequest.getSession().getAttribute("USER");

        List<Permission_TBEntity> permission_tbEntities = getUserPermission.GetPermission(userEntity.getUname());
        resultInfo.setFlag(false);

        for (Permission_TBEntity permission_tbEntity : permission_tbEntities) {
            if (permission_tbEntity.getPermission().equalsIgnoreCase("u6")){
                IPage<UserEntity> allUserData = userFusionService.getAllUserData(page);
                List<UserEntity> records = allUserData.getRecords();
                for (UserEntity record : records) {
                    Integer uid = record.getUid();
                    Long user_roleEntities1 = userFusionService.uidFindURoleCount(uid);

                    record.setURoleCount(user_roleEntities1);

                }
                resultInfo.setFlag(true);
                resultInfo.setData(allUserData);
                break;
            }else {
                resultInfo.setFlag(false);
                resultInfo.setErrorMsg("您无此权限!");
            }
        }

        packagedData.writeValue(resultInfo,httpServletResponse);
    }

    @RequestMapping("getAllRole")
    public void getAllRole(@RequestParam int page ,HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException {

        ResultInfo resultInfo = new ResultInfo();
        PackagedData packagedData = new PackagedDataImpl();
        UserEntity userEntity = (UserEntity)httpServletRequest.getSession().getAttribute("USER");

        List<Permission_TBEntity> permission_tbEntities = getUserPermission.GetPermission(userEntity.getUname());
        resultInfo.setFlag(false);

        for (Permission_TBEntity permission_tbEntity : permission_tbEntities) {
            if (permission_tbEntity.getPermission().equalsIgnoreCase("u7")){
                IPage<URole_TBEntity> allRole = userFusionService.getAllRole(page);
                List<URole_TBEntity> records = allRole.getRecords();

                for (URole_TBEntity record : records) {


                    Integer uRoleId = record.getUroleId();
                    Long permissionICount = userFusionService.uRoleIdFindPermissionId(uRoleId);
                    Long userCount = userFusionService.uRoleIdFindUserId(uRoleId);

                    record.setPermissionCount(permissionICount);
                    record.setUserCont(userCount);
                }

                resultInfo.setFlag(true);
                resultInfo.setData(allRole);
                break;
            }else {
                resultInfo.setFlag(false);
                resultInfo.setErrorMsg("您无此权限!");
            }
        }
        packagedData.writeValue(resultInfo,httpServletResponse);
    }

    @RequestMapping("getUserDeleteStatus")
    public void getUserDeleteStatus(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException {
        List<DeleteStatusEntity> deleteStatusEntities = userFusionService.getUserDeleteStatus();
        ResultInfo resultInfo = new ResultInfo();
        resultInfo.setData(deleteStatusEntities);
        PackagedData packagedData = new PackagedDataImpl();
        packagedData.writeValue(resultInfo,httpServletResponse);
    }

    @RequestMapping("setUserDeleteStatus")
    public void setUserDeleteStatus(@RequestParam String uname,@RequestParam String userDeleteStatusValue,HttpServletResponse httpServletResponse,HttpServletRequest httpServletRequest) throws IOException {
        boolean b = userFusionService.setUserDeleteStatus(uname,userDeleteStatusValue);
        setResultsInfo(httpServletResponse, b);
    }

    @RequestMapping("setUserGroup")
    public void setUserGroup(@RequestParam String uname,@RequestParam String group,HttpServletResponse httpServletResponse,HttpServletRequest httpServletRequest) throws IOException {
        Group_Type group_type = CalculationIsType.calculationIsGroupType(group);
        Integer integer = CalculationIsType.calculationIsGroupTypeToMySql(group_type);
        boolean b = userFusionService.setUserGroup(uname,integer);
        setResultsInfo(httpServletResponse, b);

    }

    private void setResultsInfo(HttpServletResponse httpServletResponse, boolean b) throws IOException {
        ResultInfo resultInfo = new ResultInfo();
        if (b){
            resultInfo.setFlag(true);
            resultInfo.setErrorMsg("修改成功");
        }else {
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("修改失败");
        }
        PackagedData packagedData = new PackagedDataImpl();
        packagedData.writeValue(resultInfo,httpServletResponse);
    }

    @RequestMapping("viewURoles")
    public void viewURoles(@RequestParam int page ,@RequestParam String uname,HttpServletResponse httpServletResponse,HttpServletRequest httpServletRequest) throws IOException {
        UserEntity userEntity = userLoginService.findUser(uname);
        List<User_RoleEntity> user_roleEntities = userFusionService.uidFindURole(userEntity.getUid(), page);
        List<URole_TBEntity> uRole_tbEntities = new ArrayList<>();
        for (User_RoleEntity user_roleEntity : user_roleEntities) {
            Integer uroleId = user_roleEntity.getUroleId();
            URole_TBEntity uRole_tbEntity = userFusionService.uRidFindUR(uroleId);
            uRole_tbEntities.add(uRole_tbEntity);
        }
        IPage<URole_TBEntity> iPage = new Page<>(page,10);

        iPage.setRecords(uRole_tbEntities);
        iPage.setPages(uRole_tbEntities.size() % 10 == 0 ? uRole_tbEntities.size() / 10 : (uRole_tbEntities.size() / 10) + 1 );
        iPage.setTotal(uRole_tbEntities.size());

        ResultInfo resultInfo = new ResultInfo();
        PackagedData packagedData = new PackagedDataImpl();
        resultInfo.setFlag(true);
        resultInfo.setData(iPage);
        packagedData.writeValue(resultInfo,httpServletResponse);
    }

    @RequestMapping("findAllUserRole")
    public void findAllUserRole(@RequestParam int page,@RequestParam String uname,HttpServletResponse httpServletResponse,HttpServletRequest httpServletRequest) throws IOException {
        IPage<URole_TBEntity> iPage = userFusionService.findAllUserRole(page,10);
        UserEntity userEntity = userLoginService.findUser(uname);
        List<User_RoleEntity> user_roleEntities = userFusionService.uidFindURole(userEntity.getUid(), page);

        ResultInfo resultInfo = new ResultInfo();
        PackagedData packagedData = new PackagedDataImpl();
        resultInfo.setFlag(true);
        resultInfo.setData(iPage);
        resultInfo.setData2(user_roleEntities);
        packagedData.writeValue(resultInfo,httpServletResponse);
    }

    @RequestMapping("allocationRole")
    public void allocationRole(@RequestParam List<String> roleContext,@RequestParam List<String> roleStatusArr,@RequestParam String uname) {
        LinkedHashMap<String,String> hashMap = new LinkedHashMap<>();
        ResultInfo resultInfo = new ResultInfo();
        PackagedData packagedData = new PackagedDataImpl();
        for (int i = 0; i < roleContext.size(); i++) {
            hashMap.put(roleContext.get(i).replace("\"", "").replace("[","").replace("]",""),
                    roleStatusArr.get(i).replace("\"", "").replace("[","").replace("]",""));
        }



        LinkedHashMap<Integer,Integer> integerIntegerLinkedHashMap = new LinkedHashMap<>();
        UserEntity userEntity = userLoginService.findUser(uname);
        List<URole_TBEntity> allUserRole = userFusionService.findAllUserRole();
        for (URole_TBEntity uRole_tbEntity : allUserRole) {
            for (Map.Entry<String, String> stringStringEntry : hashMap.entrySet()) {
                if (stringStringEntry.getKey().equalsIgnoreCase(uRole_tbEntity.getAlias())){
                    System.out.println(uRole_tbEntity.getUroleId());
                    System.out.println(Integer.parseInt(stringStringEntry.getValue()));
                    integerIntegerLinkedHashMap.put(uRole_tbEntity.getUroleId(), Integer.parseInt(stringStringEntry.getValue()));
                }
            }
        }

        boolean b = userFusionService.allocationRole(integerIntegerLinkedHashMap, userEntity.getUid());
        if (b){
            resultInfo.setFlag(true);
            resultInfo.setErrorMsg("授权成功！");
        }else {
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("授权失败！");
        }
    }

    @RequestMapping("viewUser")
    public void viewUser(@RequestParam int page,@RequestParam String role,HttpServletResponse httpServletResponse,HttpServletRequest httpServletRequest) throws IOException {
        URole_TBEntity rid = userFusionService.roleFindRid(role);
        ResultInfo resultInfo = new ResultInfo();
        PackagedData packagedData = new PackagedDataImpl();

        List<User_RoleEntity> user_roleEntities = userFusionService.ridFindURList(rid,page);
        List<UserEntity> userEntities = new ArrayList<>();

        for (User_RoleEntity user_roleEntity : user_roleEntities) {
            System.out.println(user_roleEntity.getUserId());
            UserEntity userEntity = userLoginService.uidFindUser(user_roleEntity.getUserId());

            userEntities.add(userEntity);
        }
        System.out.println(userEntities);
        IPage<UserEntity> iPage = new Page<>(page,10);

        iPage.setRecords(userEntities);
        iPage.setPages(userEntities.size() % 10 == 0 ? userEntities.size() / 10 : (userEntities.size() / 10) + 1 );
        iPage.setTotal(userEntities.size());
        resultInfo.setData(iPage);
        packagedData.writeValue(resultInfo,httpServletResponse);
    }

    @RequestMapping("viewPermission")
    public void viewPermission(@RequestParam int page,@RequestParam String role,HttpServletResponse httpServletResponse,HttpServletRequest httpServletRequest) throws IOException {
        ResultInfo resultInfo = new ResultInfo();
        PackagedData packagedData = new PackagedDataImpl();
        IPage<Permission_TBEntity> permission_tbEntityIPage = userFusionService.findAllPermission(page);
        URole_TBEntity uRole_tbEntity = userFusionService.roleFindRid(role);
        List<Urole_PermissionEntity> urole_permissionEntities = userFusionService.uRidFindURPermission(uRole_tbEntity.getUroleId());
        resultInfo.setData(permission_tbEntityIPage);
        resultInfo.setData2(urole_permissionEntities);
        packagedData.writeValue(resultInfo,httpServletResponse);

    }

    @RequestMapping("setRoleDeleteUser")
    public void setRoleDeleteUser(@RequestParam List<String> unameArr,@RequestParam String role,HttpServletResponse httpServletResponse,HttpServletRequest httpServletRequest) {
        for (String s : unameArr) {
            String uname = s.replace("\"", "").replace("[","").replace("]","");
            UserEntity userEntity = userLoginService.findUser(uname);
            URole_TBEntity uRole_tbEntity = userFusionService.roleFindRid(role);
            userFusionService.setRoleDeleteUser(userEntity.getUid(),uRole_tbEntity.getUroleId());
        }
    }

    @RequestMapping("setDeleteRolePermissionBtn")
    public void setDeleteRolePermissionBtn(@RequestParam String role,@RequestParam List<String> authArr,@RequestParam List<String> authTemplateArr,HttpServletResponse httpServletResponse,HttpServletRequest httpServletRequest) {

            URole_TBEntity uRole_tbEntity = userFusionService.roleFindRid(role);
            userFusionService.setDeleteRolePermissionBtn(uRole_tbEntity.getUroleId(),authArr,authTemplateArr);

    }
}
